﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Printing;

namespace SimpleNotePad
{
    public partial class SimpleNotePadForm : Form
    {
        private bool _documentChanged = false;

        public SimpleNotePadForm()
        {
            InitializeComponent();
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveDocumentNeedForm dialog = new SaveDocumentNeedForm();
            DialogResult result = dialog.ShowDialog();

            switch (result)
            {
                case DialogResult.Yes:
                    {
                        MenuFileSaveAs();
                        break;
                    }
                case DialogResult.Cancel:
                    {
                        return;
                    }
            }

            richTextBox1.Clear();
            toolStripStatusLabel2.Text = "";
            _documentChanged = false;
        }

        ///<summary>
        ///Open existing file
        ///<summary>

        private void MenuFileOpen()
        {
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && openFileDialog1.FileName.Length > 0)
            {
                try
                {
                    richTextBox1.LoadFile(openFileDialog1.FileName,
                        RichTextBoxStreamType.RichText);
                }
                
                catch(Exception)
                {
                    richTextBox1.LoadFile(openFileDialog1.FileName, 
                        RichTextBoxStreamType.PlainText);
                }

                this.Text = "Файл ["+openFileDialog1.FileName+"]";
            }
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveDocumentNeedForm dialog = new SaveDocumentNeedForm();
            DialogResult result = dialog.ShowDialog();

            switch (result)
            {
                case DialogResult.Yes:
                    {
                        MenuFileSaveAs();
                        break;
                    }
                case DialogResult.Cancel:
                    {
                        return;
                    }
            }

            MenuFileOpen();

            toolStripStatusLabel2.Text = "";
            _documentChanged = false;
        }

        private void MenuFileSaveAs()
        {
            if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK
                && openFileDialog1.FileName.Length > 0)
            {
                richTextBox1.SaveFile(saveFileDialog1.FileName);
                this.Text = "Файл [" + openFileDialog1.FileName + "]";
                _documentChanged = false;
            }
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MenuFileSaveAs();
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MenuFileSaveAs();

            toolStripStatusLabel2.Text = "";
        }

        /// <summary>
        /// Set print properties of page
        /// </summary>

        private void MenuFulePageSetup()
        {
            pageSetupDialog1.ShowDialog();
        }

        private void pageSetupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MenuFulePageSetup();
        }


        private StringReader _myStringReader;// reader for prnting
        private int _printPageNumber;// number of current page

        /// <summary>
        /// Show preview page of pinted page
        /// </summary>

        private void MenuFilePrintPreview()
        {
            _printPageNumber = 1;

            string _strText = richTextBox1.Text;
            _myStringReader = new StringReader(_strText);
            Margins _margins = new Margins(100, 50, 50, 50);

            printDocument1.DefaultPageSettings.Margins = _margins;
            printPreviewDialog1.ShowDialog();

            _myStringReader.Close();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            MenuFilePrintPreview();
        }

        private void MenuFilePrintDocument()
        {
            _printPageNumber = 1;

            string _strText = richTextBox1.Text;
            _myStringReader = new StringReader(_strText);
            Margins _margins = new Margins(100, 50, 50, 50);

            printDocument1.DefaultPageSettings.Margins = _margins;

            if (printDialog1.ShowDialog() == DialogResult.OK)
            {
                this.printDocument1.Print();
            }

            _myStringReader.Close();
        }

        private void printToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintPageEventArgs _args = (PrintPageEventArgs) e;
            
            int _lineCount = 0;// counter of lines
            float _linesPerPage = 0;// count of lines on one page
            float _linePosition = 0;// current  position while printing
                                    // on the vertical axis
            string currentLine = null; // text of current line

            Font _printFont = this.richTextBox1.Font;// font for printing text

            SolidBrush _brush = new SolidBrush(Color.Black);// Brush for printing text

            float _leftMargin = _args.MarginBounds.Left;// Size for left backdown

            float _topMargin = _args.MarginBounds.Top +
                3 * _printFont.GetHeight(_args.Graphics);// Size for top backdown

            // calculates count of lines on one page considering backdowns
            _linesPerPage = (_args.MarginBounds.Height -
                6 * _printFont.GetHeight(_args.Graphics)) /
                _printFont.GetHeight(_args.Graphics);                                                     

            // cycle for printing all lines on page 
            while (_lineCount < _linesPerPage && 
                (currentLine = _myStringReader.ReadLine())!=null)
            {
                // calculates position for next line 
                _linePosition = _topMargin + (_lineCount *
                    _printFont.GetHeight(_args.Graphics));
                // printinf next line
                _args.Graphics.DrawString(currentLine, _printFont, _brush, 
                    _leftMargin, _linePosition, new StringFormat());
                // go to next line
                _lineCount++;
            }

            // printing the headers of page

            string _myStringPageNumber = "Page "+ _printPageNumber.ToString();

            // calculates size of rectangle of top heder
            SizeF _stringSize = new SizeF();
            _stringSize = _args.Graphics.MeasureString(_myStringPageNumber, _printFont,
                _args.MarginBounds.Right - _args.MarginBounds.Left);

            //printing number of page 
            _args.Graphics.DrawString(_myStringPageNumber, _printFont, _brush,
                _args.MarginBounds.Right - _stringSize.Width, _args.MarginBounds.Top, 
                new StringFormat());

            // printing name of doc-file
            _args.Graphics.DrawString(this.Text, _printFont, _brush, 
                _args.MarginBounds.Left, _args.MarginBounds.Top, new StringFormat());

            // Brash for painting horizontal lines to spret top heder
            Pen _hederPen = new Pen(Color.Black);
            _hederPen.Width = 2;

            // paint the line spret top heder
            _args.Graphics.DrawLine(_hederPen, _leftMargin,
                _args.MarginBounds.Top + _printFont.GetHeight(_args.Graphics) + 3,
                _args.MarginBounds.Right, _args.MarginBounds.Top + 
                _printFont.GetHeight(_args.Graphics) + 3);

            // paint the line witch spret lower heder
            _args.Graphics.DrawLine(_hederPen, _leftMargin,
                _args.MarginBounds.Bottom -3, _args.MarginBounds.Right,
                _args.MarginBounds.Bottom -3 );

            // if all lines on this page printed, go to next
            if (currentLine == null)
            {
                _args.HasMorePages = true;
                _printPageNumber++;
            }
            else
                _args.HasMorePages = false;
            _brush.Dispose();
            _hederPen.Dispose();
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            _documentChanged = true;
            toolStripStatusLabel2.Text = Properties.Resources._changed;
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveDocumentNeedForm dialog = new SaveDocumentNeedForm();
            DialogResult result = dialog.ShowDialog();

            switch (result)
            {
                case DialogResult.Yes:
                    {
                        MenuFileSaveAs();
                        break;
                    }
                case DialogResult.Cancel:
                    {
                        return;
                    }
            }

            this.Close();
        }

        protected override void Dispose(bool disposing)
        {
            if (_documentChanged == true)
            {
                MenuFileSaveAs();
            }
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        private void redoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Redo();
        }

        private void undoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Undo();
        }

        private void cutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Cut();
        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Copy();
        }

        private void pToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Paste();
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Cut();
        }

        private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.SelectAll();
        }

        private void fintToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (fontDialog1.ShowDialog() == DialogResult.OK)
            {
                richTextBox1.SelectionFont = fontDialog1.Font;
            }
        }

        private void colorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (colorDialog1.ShowDialog() == DialogResult.OK)
            {
                richTextBox1.SelectionColor = colorDialog1.Color;
            }
        }

        /// <summary>
        /// Setting a bold style
        /// </summary>
        
        private void SetBold()
        {
            if (richTextBox1.SelectionFont != null)
            {
                System.Drawing.Font _currentFont = richTextBox1.SelectionFont;
                System.Drawing.FontStyle _newFontStyle;

                if (richTextBox1.SelectionFont.Bold == true)
                {
                    _newFontStyle = FontStyle.Regular;
                }
                else 
                {
                    _newFontStyle = FontStyle.Bold;
                }

                richTextBox1.SelectionFont = new Font(_currentFont.FontFamily, _currentFont.Size,
                    _newFontStyle);

                CheckMenuCharakterStyle();
              } 
        }

        /// <summary>
        /// Checking of charakters style
        /// </summary>

        private void CheckMenuCharakterStyle()
        {
            if (richTextBox1.SelectionFont.Bold == true)
            {
                boldToolStripMenuItem.Checked = true;
            }
            else
            {
                boldToolStripMenuItem.Checked = false;
            }

            if (richTextBox1.SelectionFont.Italic == true)
            {
                italicToolStripMenuItem.Checked = true;
            }
            else
            {
                italicToolStripMenuItem.Checked = false;
            }

            if (richTextBox1.SelectionFont.Underline == true)
            {
                underlineToolStripMenuItem.Checked = true;
            }
            else
            {
                underlineToolStripMenuItem.Checked = false;
            }

            if (richTextBox1.SelectionFont.Strikeout == true)
            {
                strikeoutToolStripMenuItem.Checked = true;
            }
            else
            {
                strikeoutToolStripMenuItem.Checked = false;
            }
        }

        /// <summary>
        /// Setting a italic style
        /// </summary>

        private void SetItalic()
        {
            if (richTextBox1.SelectionFont != null)
            {
                System.Drawing.Font _currentFont = richTextBox1.SelectionFont;
                System.Drawing.FontStyle _newFontStyle;

                if (richTextBox1.SelectionFont.Italic == true)
                {
                    _newFontStyle = FontStyle.Regular;
                }
                else
                {
                    _newFontStyle = FontStyle.Italic;
                }

                richTextBox1.SelectionFont = new Font(_currentFont.FontFamily, _currentFont.Size,
                    _newFontStyle);

                CheckMenuCharakterStyle();
            }
        }

        /// <summary>
        /// Setting a underline style
        /// </summary>

        private void SetUnderline()
        {
            if (richTextBox1.SelectionFont != null)
            {
                System.Drawing.Font _currentFont = richTextBox1.SelectionFont;
                System.Drawing.FontStyle _newFontStyle;

                if (richTextBox1.SelectionFont.Underline == true)
                {
                    _newFontStyle = FontStyle.Regular;
                }
                else
                {
                    _newFontStyle = FontStyle.Underline;
                }

                richTextBox1.SelectionFont = new Font(_currentFont.FontFamily, _currentFont.Size,
                    _newFontStyle);

                CheckMenuCharakterStyle();
            }
        }

        /// <summary>
        /// Setting a strikeout style
        /// </summary>

        private void SetStrikeout()
        {
            if (richTextBox1.SelectionFont != null)
            {
                System.Drawing.Font _currentFont = richTextBox1.SelectionFont;
                System.Drawing.FontStyle _newFontStyle;

                if (richTextBox1.SelectionFont.Strikeout == true)
                {
                    _newFontStyle = FontStyle.Regular;
                }
                else
                {
                    _newFontStyle = FontStyle.Strikeout;
                }

                richTextBox1.SelectionFont = new Font(_currentFont.FontFamily, _currentFont.Size,
                    _newFontStyle);

                CheckMenuCharakterStyle();
            }
        }

        private void boldToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetBold();
        }

        private void italicToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetItalic();
        }

        private void underlineToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetUnderline();
        }

        private void strikeoutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetStrikeout();
        }

        private void leftToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            richTextBox1.SelectionAlignment = HorizontalAlignment.Left;
        }

        private void rightToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            richTextBox1.SelectionAlignment = HorizontalAlignment.Right;
        }

        private void centerToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            richTextBox1.SelectionAlignment = HorizontalAlignment.Center;
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form _aboutForm = new HelpAboutForm();
            _aboutForm.ShowDialog();
        }

        private void registerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RegisterForm dialog = new RegisterForm();

            if (DialogResult.Yes == dialog.ShowDialog())
            {
                string body = Properties.Resources.Register_Data;

                body += "Name :" + dialog.UserName;
                body += ", Email" + dialog.UserEmail;
                body += ", Level :" + dialog.UserLevel;
                body += ", Gender :" + dialog.UserGender;
                body += ", FavoriteOS :" + dialog.FavoriteOS;
                body += ", Send News :" + dialog.SendNews;
                body += ", Enewspaper :" + dialog.Enewspaper;
                body += ", BirthDay :" + dialog.UserDOB;
                body += ", Comment :" + dialog.UserComment;

                System.Diagnostics.Process.Start(
                    "mailto:"+Properties.Resources.Email+"?subject=Регистация&body=" + body);
            }
        }
    }
}
